/**
 * Created by Tuffy on 16/6/6.
 */
'use strict';

adminCtrl

.controller('UserTruckCtrl', ['$rootScope', '$scope', '$state', 'UserTruckService', function ($rootScope, $scope, $state, UserTruckService) {

    $scope.page = {
        pageNo: 1,
        totalPage: 0
    };

    $scope.truckInfo = [];

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            loadData();
        }
    };

    // 初始化数据列表
    function loadData() {
        UserTruckService.list({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize
        }).success(function (result) {
            if (result.success) {
                $scope.truckInfo = result.data.truckInfo;
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    }

    loadData();
}])

.controller('UserCtrl', ['$rootScope', '$scope', 'UserService', function ($rootScope, $scope, UserService) {

    // 用户对象
    $scope.userObj = {
        list: [],
        init: function () {
            var that = this;
            UserService.list()
                .success(function (result) {
                    if (result.success) {
                        that.list = result.data;
                    }
                })
        },
        remove: function (id) {
            var that = this;
            var index = layer.confirm('删除该用户？', {
                btn: ['确定','取消'], //按钮,
                skin: 'admin-confirm-btn-class',
                title: '删除用户'
            }, function(){
                UserService.remove(id)
                    .success(function (result) {
                        if (result.success) {
                            layer.msg('删除成功');
                            history.go(-1);
                        } else {
                            layer.msg(result.message);
                        }
                        layer.close(index);
                    })
            }, function(){
                //
            });
        }
    };

    // 初始化
    $scope.userObj.init();
}])

.controller('UserEditCtrl', ['$rootScope', '$scope', '$state', 'UserService', 'RoleService', function ($rootScope, $scope, $state, UserService, RoleService) {

    var id = $state.params.id;

    // banner对象
    $scope.userObj = {
        newPassword: null,
        roleList: [],
        enabledList: [{
            code: 'T',
            name: '是'
        }, {
            code: 'F',
            name: '否'
        }],
        info: {},
        byId: function () {
            var that = this;
            if (id) {
                UserService.byId(id)
                    .success(function (result) {
                        if (result.success) {
                            that.info = result.data;
                        }
                    });
            }
        },
        save: function () {
            UserService.save({
                id: $scope.userObj.info.id,
                username: $scope.userObj.info.username,
                password: $scope.userObj.info.password,
                newPassword: $scope.userObj.newPassword,
                roleId: $scope.userObj.info.roleId,
                enabled: $scope.userObj.info.enabled
            })
                .success(function (result) {
                    if (result.success) {
                        layer.msg('编辑成功');
                        history.go(-1);
                    } else {
                        layer.msg(result.message);
                    }
                })
        },
        roles: function () {
            var that = this;
            RoleService.all()
                .success(function (result) {
                    if (result.success) {
                        that.roleList = result.data;
                    }
                })
        }
    };

    // 初始化
    $scope.userObj.byId();
    $scope.userObj.roles();
}])

.controller('UserOilCardCtrl', ['$rootScope', '$scope', 'UserOilCardService', function ($rootScope, $scope, UserOilCardService) {
    // 查询条件
    $scope.queryOilCard = {
        phone: '',
        cardCode: ''
    };

    // 更新对象
    $scope.updateOilCardStatus = {
        id: '',
        status: ''
    };

    // 数据列表
    $scope.oilList = [];

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            $scope.loadData();
        }
    };

    // 初始化数据列表
    $scope.loadData = function (params) {
        if ('query' === params){
            $scope.userTruckObj.pageNo = 1;
            $scope.userTruckObj.pageSize = 10;
            $scope.page.pageNo = 1;
            $scope.page.totalPage = 0;
        }
        UserOilCardService.list({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize,
            phone: $scope.queryOilCard.phone,
            cardCode: $scope.queryOilCard.cardCode
        }).success(function (result) {
            if (result.success) {
                $scope.oilList = result.data.oilCard;
                angular.forEach($scope.oilList, function (item) {
                    item.statusText = Tools.getDUserOilCardStatusText(item.status);
                })
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    // 清空查询条件
    $scope.clearQuery = function () {
        $scope.queryOilCard = {
            phone: '',
            cardCode: ''
        };
        $scope.loadData('load');
    }

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    }

    //修改用户手机
    $scope.modify = function (id, status) {
        $scope.updateOilCardStatus.id = id;
        $scope.updateOilCardStatus.status = status;
        UserOilCardService.modifyStatus($scope.updateOilCardStatus)
            .success(function (result) {
                if (result.success) {
                    $rootScope.hycadmin.toast({
                        title: '操作已成功',
                        timeOut: 3000
                    });
                    $scope.loadData('load');
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
    };

    // 初始化数据
    $scope.loadData('load');
}])

.controller('UserRouteCtrl', ['$rootScope', '$scope', 'UserRouteService', 'UserService', function ($rootScope, $scope, UserRouteService, UserService) {
    // 查询条件
    $scope.queryRoute = {
        userId: '',
        orginCode: '',
        destCode: ''
    };

    // 数据列表
    $scope.routeList = [];

    // 起始地
    $scope.orginList = [];

    // 目的地
    $scope.destList = [];

    // 分供方
    $scope.subList = [];

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            $scope.loadData();
        }
    };

    // 初始化数据列表
    $scope.loadData = function (params) {
        if ('query' === params){
            $scope.userTruckObj.pageNo = 1;
            $scope.userTruckObj.pageSize = 10;
            $scope.page.pageNo = 1;
            $scope.page.totalPage = 0;
        }
        UserRouteService.list({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize,
            userId: $scope.queryRoute.userId,
            orginCode: $scope.queryRoute.orginCode,
            destCode: $scope.queryRoute.destCode
        }).success(function (result) {
            if (result.success) {
                $scope.routeList = result.data.route;
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    // 清空查询条件
    $scope.clearQuery = function () {
        $scope.queryRoute = {
            userId: '',
            orginCode: '',
            destCode: ''
        };
        $scope.loadData('load');
    };

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    };

    // 加载起始地
    function loadOrgin() {
        UserRouteService.loadProvince()
            .success(function (result) {
                if (result.success) {
                    $scope.orginList = result.data;
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
    }
    // 加载目的地
    function loadDest() {
        UserRouteService.loadProvince()
            .success(function (result) {
                if (result.success) {
                    $scope.destList = result.data;
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
    }

    function loadSubUser() {
        UserService.subList()
            .success(function (result) {
                if (result.success) {
                    $scope.subList = result.data;
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            })
    }

    // 初始化数据
    loadSubUser();
    loadOrgin();
    loadDest();
    $scope.loadData('load');
}])

.controller('UserRouteEditCtrl', ['$rootScope', '$scope', '$state', 'UserRouteService', 'UserService', function ($rootScope, $scope, $state, UserRouteService, UserService) {
    $scope.id = $state.params.id;
    $scope.routeTitle = $state.params.routeTitle;

    // 更新对象
    $scope.updateRoute = {
        id: '',
        userId: '',
        orginCode: '',
        destCode: '',
        maximumEveryDay: '',
        isEdit: true
    };

    // 起始地
    $scope.orginList = [];

    // 目的地
    $scope.destList = [];

    // 分供方
    $scope.subList = [];

    $scope.saveRoute = function () {
        if ($scope.updateRoute.maximumEveryDay > 30 || $scope.updateRoute.maximumEveryDay <= 0 || typeof $scope.updateRoute.maximumEveryDay == 'undefined') {
            $rootScope.hycadmin.toast({
                title: '每天申请的最大运单数值必须在1~30之间',
                timeOut: 3000
            });
            return;
        }
        UserRouteService.modifyRoute($scope.updateRoute)
            .success(function (result) {
                if (result.success) {
                    $rootScope.hycadmin.toast({
                        title: '操作已成功',
                        timeOut: 3000
                    });
                    $state.go('user-route-list');
                    $scope.loadData('load');
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
    };

    // 加载起始地
    function loadOrgin() {
        UserRouteService.loadProvince()
            .success(function (result) {
                if (result.success) {
                    $scope.orginList = result.data;
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
    }
    // 加载目的地
    function loadDest() {
        UserRouteService.loadProvince()
            .success(function (result) {
                if (result.success) {
                    $scope.destList = result.data;
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
    }

    function loadData() {
        if ($scope.id) {
            $scope.updateRoute.isEdit = false;
            UserRouteService.getById({
                    id: $scope.id
                }).success(function (result) {
                    if (result.success) {
                        $scope.updateRoute = result.data;
                    } else {
                        $rootScope.hycadmin.toast({
                            title: result.message,
                            timeOut: 3000
                        });
                    }
                });
        }
    }

    function loadSubUser() {
        UserService.subList()
            .success(function (result) {
                if (result.success) {
                    $scope.subList = result.data;
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            })
    }

    //初始化数据
    loadSubUser();
    loadOrgin();
    loadDest();
    loadData();

}])

.controller('UserBindDeviceCtrl', ['$rootScope', '$scope', 'UserBindDeviceService', function ($rootScope, $scope, UserBindDeviceService) {
    // 查询条件
    $scope.query = {
        phone: ''
    };

    // 数据列表
    $scope.deviceList = [];

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            $scope.loadData();
        }
    };

    // 初始化数据列表
    $scope.loadData = function (params) {
        if ('query' === params){
            $scope.userTruckObj.pageNo = 1;
            $scope.userTruckObj.pageSize = 10;
            $scope.page.pageNo = 1;
            $scope.page.totalPage = 0;
        }
        UserBindDeviceService.getList({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize,
            phone: $scope.query.phone
        }).success(function (result) {
            if (result.success) {
                $scope.deviceList = result.data.device;
                angular.forEach($scope.deviceList, function (item) {
                    item.bindStatusText = Tools.getSUserBindDeviceStatusText(item.bindStatus);
                });
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };

    // 清空查询条件
    $scope.clearQuery = function () {
        $scope.query = {
            phone: ''
        };
        $scope.loadData('load');
    };

    // 解绑
    $scope.unbind = function (id) {
        if (id == null || id == 0) {
            return;
        }
        UserBindDeviceService.unbind({
            id: id
        }).success(function (result) {
            if (result.success) {
                $rootScope.hycadmin.toast({
                    title: '解绑成功',
                    timeOut: 3000
                });
                $scope.loadData('load');
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    };

    // 初始化数据
    $scope.loadData('load');
}])

    .controller('UploadOtdTrackingCtl', ['$rootScope', '$scope', '$modal', 'FileUploader', function ($rootScope, $scope, $modal, FileUploader) {

        var uploader = $scope.uploader = new FileUploader({
            url:'/upload/excelotd',
            method: 'POST',
            fileName: 'file'
        });
        // a sync filter
        uploader.filters.push({
            name: 'syncFilter',
            fn: function (item /*{File|FileLikeObject}*/, options) {
                // console.log('syncFilter');
                return this.queue.length < 10;
            }
        });

        uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
            // console.info('onWhenAddingFileFailed', item, filter, options);
        };
        uploader.onAfterAddingFile = function (fileItem) {
            fileItem.upload();
            // console.info('onAfterAddingFile', fileItem);
        };
        uploader.onAfterAddingAll = function (addedFileItems) {
            // console.info('onAfterAddingAll', addedFileItems);
        };
        uploader.onBeforeUploadItem = function (item) {
            // console.info('onBeforeUploadItem', item);
        };
        uploader.onProgressItem = function (fileItem, progress) {
            // console.info('onProgressItem', fileItem, progress);
        };
        uploader.onProgressAll = function (progress) {
            // console.info('onProgressAll', progress);
        };
        uploader.onSuccessItem = function (fileItem, response, status, headers) {
            // console.info('onSuccessItem', fileItem, response, status, headers);
        };
        uploader.onErrorItem = function (fileItem, response, status, headers) {
            // console.info('onErrorItem', fileItem, response, status, headers);
        };
        uploader.onCancelItem = function (fileItem, response, status, headers) {
            // console.info('onCancelItem', fileItem, response, status, headers);
        };
        uploader.onCompleteItem = function (fileItem, response, status, headers) {

            // console.info('onCompleteItem', fileItem, response, status, headers);
            layer.msg(response.message);
        };
        uploader.onCompleteAll = function () {
            // console.info('onCompleteAll');
        };

        // console.info('uploader', uploader);


    }])

    .controller('UploadCustomOtdCtl', ['$rootScope', '$scope', '$modal', 'FileUploader', function ($rootScope, $scope, $modal, FileUploader) {

        var uploader = $scope.uploader = new FileUploader({
            url:'/upload/excelcustomotd',
            method: 'POST',
            fileName: 'file'
        });
        // a sync filter
        uploader.filters.push({
            name: 'syncFilter',
            fn: function (item /*{File|FileLikeObject}*/, options) {
                console.log('syncFilter');
                return this.queue.length < 10;
            }
        });
        // CALLBACKS

        uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
            // console.info('onWhenAddingFileFailed', item, filter, options);
        };
        uploader.onAfterAddingFile = function (fileItem) {
            fileItem.upload();
            // console.info('onAfterAddingFile', fileItem);
        };
        uploader.onAfterAddingAll = function (addedFileItems) {
            // console.info('onAfterAddingAll', addedFileItems);
        };
        uploader.onBeforeUploadItem = function (item) {
            // console.info('onBeforeUploadItem', item);
        };
        uploader.onProgressItem = function (fileItem, progress) {
            // console.info('onProgressItem', fileItem, progress);
        };
        uploader.onProgressAll = function (progress) {
            // console.info('onProgressAll', progress);
        };
        uploader.onSuccessItem = function (fileItem, response, status, headers) {
            // console.info('onSuccessItem', fileItem, response, status, headers);
        };
        uploader.onErrorItem = function (fileItem, response, status, headers) {
            // console.info('onErrorItem', fileItem, response, status, headers);
        };
        uploader.onCancelItem = function (fileItem, response, status, headers) {
            // console.info('onCancelItem', fileItem, response, status, headers);
        };
        uploader.onCompleteItem = function (fileItem, response, status, headers) {

            // console.info('onCompleteItem', fileItem, response, status, headers);
            layer.msg(response.message);
        };
        uploader.onCompleteAll = function () {
            // console.info('onCompleteAll');
        };

        // console.info('uploader', uploader);


    }])